import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Button, Wrapper, Menu, MenuItem} from 'react-aria-menubutton';
import _ from 'lodash';
import DropdownList from '../widgets/DropdownList';
import RadioButtonList from '../widgets/RadioButtonList';

export default class CoderSelector extends Component {
  static propTypes = {
    coder: PropTypes.object,
    coders: PropTypes.array,
    onSelection: PropTypes.func,
    onOptionChange: PropTypes.func,
  }

  handleSelection = (value, event) => {
    this.props.onSelection && this.props.onSelection(value);
  }

  updateOption = name => {
    return value => {
      const coder = this.props.coder;
      coder.options[name] = value;
      this.props.onOptionChange && this.props.onOptionChange(coder);
    };
  }

  renderCoderOptions() {
    let widgets = [];
    const coder = this.props.coder;
    if (coder) {
      const options = coder.constructor.Options;
      _.forEach(options, (widget, name) => {
        const value = coder.options[name];
        switch(widget.type) {
          case 'radio':
            widgets.push(<RadioButtonList key={name} options={widget.options} value={value} onChange={this.updateOption(name)} />);
            break;
          case 'menu':
            widgets.push(<DropdownList key={name} options={widget.options} value={value} onChange={this.updateOption(name)} />);
            break;
          case 'switch':
            widgets.push(<label key={name}><input type="checkbox" value={value} onChange={e => this.updateOption(name)(e.target.checked)} />{widget.label}</label>);
            break;
        }
      });
    }
    return widgets;
  }

  render() {
    const selected = this.props.coder;
    const menuItems = this.props.coders.map((coder, i) => {
      let itemClass = 'AriaMenuButton-menuItem';
      if (selected === coder) {
        itemClass += ' is-selected';
      }
      return (
        <li key={i} className='AriaMenuButton-menuItemWrapper'>
          <MenuItem className={itemClass} value={coder}>
            {coder.constructor.Name}
          </MenuItem>
        </li>
      );
    });
    return (
      <div className="CoderSelector">
        <Wrapper className='AriaMenuButton' onSelection={this.handleSelection}>
          <Button className='AriaMenuButton-trigger'>{selected ? selected.constructor.Name : '<%= UIText.choose %>'}</Button>
          <Menu>
            <ul className='AriaMenuButton-menu'>{menuItems}</ul>
          </Menu>
        </Wrapper>
        {this.renderCoderOptions()}
      </div>
    );
  }
}
